<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang>
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="mobx-state-tree,">





  <link rel="alternate" href="/blog/atom.xml" title="编程那点事" type="application/atom+xml">






<meta name="description" content="预备知识在正式进入主题前，你需要确认一下，是否已经掌握下面几个工具和库的使用：  MobX：这是MST的核心，MST中存储的响应式“状态”都是MobX的Observable React：使用React来测试MST的功能非常简单 TypeScript：后文中会使用TS来编写示例代码，TS强大的智能提示和类型检查，有助于快速掌握MST的API  上面列举的工具和库都有非常丰富的文档和教程，不太熟悉的同">
<meta name="keywords" content="mobx-state-tree">
<meta property="og:type" content="article">
<meta property="og:title" content="[MobX State Tree数据组件化开发][1]：MST基础">
<meta property="og:url" content="https://lhweb.gitee.io/blog/2019/10/07/MobX-State-Tree数据组件化开发-1-：MST基础/index.html">
<meta property="og:site_name" content="编程那点事">
<meta property="og:description" content="预备知识在正式进入主题前，你需要确认一下，是否已经掌握下面几个工具和库的使用：  MobX：这是MST的核心，MST中存储的响应式“状态”都是MobX的Observable React：使用React来测试MST的功能非常简单 TypeScript：后文中会使用TS来编写示例代码，TS强大的智能提示和类型检查，有助于快速掌握MST的API  上面列举的工具和库都有非常丰富的文档和教程，不太熟悉的同">
<meta property="og:locale" content="default">
<meta property="og:image" content="https://lhweb.gitee.io/blog/2019/10/07/MobX-State-Tree数据组件化开发-1-：MST基础/1687eceac84b11ca.jpg">
<meta property="og:image" content="https://lhweb.gitee.io/blog/2019/10/07/MobX-State-Tree数据组件化开发-1-：MST基础/16882cfe6d826fff.jpg">
<meta property="og:image" content="https://lhweb.gitee.io/blog/2019/10/07/MobX-State-Tree数据组件化开发-1-：MST基础/168831d879355c88.jpg">
<meta property="og:image" content="https://lhweb.gitee.io/blog/2019/10/07/MobX-State-Tree数据组件化开发-1-：MST基础/168837fdfbd02e5d.jpg">
<meta property="og:updated_time" content="2019-10-07T10:20:43.712Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="[MobX State Tree数据组件化开发][1]：MST基础">
<meta name="twitter:description" content="预备知识在正式进入主题前，你需要确认一下，是否已经掌握下面几个工具和库的使用：  MobX：这是MST的核心，MST中存储的响应式“状态”都是MobX的Observable React：使用React来测试MST的功能非常简单 TypeScript：后文中会使用TS来编写示例代码，TS强大的智能提示和类型检查，有助于快速掌握MST的API  上面列举的工具和库都有非常丰富的文档和教程，不太熟悉的同">
<meta name="twitter:image" content="https://lhweb.gitee.io/blog/2019/10/07/MobX-State-Tree数据组件化开发-1-：MST基础/1687eceac84b11ca.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://lhweb.gitee.io/blog/2019/10/07/MobX-State-Tree数据组件化开发-1-：MST基础/">





  <title>[MobX State Tree数据组件化开发][1]：MST基础 | 编程那点事</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">编程那点事</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://lhweb.gitee.io/blog/blog/2019/10/07/MobX-State-Tree数据组件化开发-1-：MST基础/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="lhweb">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="编程那点事">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">[MobX State Tree数据组件化开发][1]：MST基础</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-10-07T17:27:12+08:00">
                2019-10-07
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="预备知识"><a href="#预备知识" class="headerlink" title="预备知识"></a>预备知识</h2><p>在正式进入主题前，你需要确认一下，是否已经掌握下面几个工具和库的使用：</p>
<ul>
<li>MobX：这是MST的核心，MST中存储的响应式“状态”都是MobX的Observable</li>
<li>React：使用React来测试MST的功能非常简单</li>
<li>TypeScript：后文中会使用TS来编写示例代码，TS强大的智能提示和类型检查，有助于快速掌握MST的API</li>
</ul>
<p>上面列举的工具和库都有非常丰富的文档和教程，不太熟悉的同学最好先自学一下。</p>
<h2 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h2><p>MST依赖MobX。</p>
<p>项目中执行yarn add mobx mobx-state-tree即可完成安装。</p>
<p>MobX有两个版本，新版本需要浏览器Proxy支持，一些老旧的浏览器并不支持，需要兼容老浏览器的请安装mobx@4：yarn add mobx@4 mobx-state-tree。</p>
<h2 id="Type、Model"><a href="#Type、Model" class="headerlink" title="Type、Model"></a>Type、Model</h2><p>使用MST来维护状态，首先需要让MST知道，这个状态的结构是什么样的。</p>
<p>MST内建了一个类型机制。通过类型的组合就可以定义出整个状态的形状。</p>
<p>并且，在开发环境下，MST可以通过这个定义好的形状，来判断状态的值和形状与其对应的类型是否匹配，确保状态的类型与预期一致，这有助于在开发时及时发现数据类型的问题：</p>
<p><img src="/blog/2019/10/07/MobX-State-Tree数据组件化开发-1-：MST基础/1687eceac84b11ca.jpg" alt></p>
<p>MST提供的一个重要对象就是types，在这个对象中，包含了基础的元类型（primitives types），如string、boolean、number，还包含了一些复杂类型的工厂方法和工具方法，常用的有model、array、map、optional等。</p>
<p>model是一个types中最重要的一个type，使用types.model方法得到的就是Model，在Model中，可以包含多个type或者其他Model。</p>
<p>一个Model可以看作是一个节点（Node），节点之间相互组合，就构造出了整棵状态树（State Tree）。</p>
<p>MST可用的类型和类型方法非常多，这里不一一列举，可以在这里查看完整的列表。</p>
<p>完成Model的定义后，可以使用Model.create方法获得Model的实例。Model.create可以传入两个参数，第一个是Model的初始状态值，第二个参数是可选参数，表示需要给Model及子Model的env对象（环境配置对象），env用于实现简单的依赖注入功能，在后续文章中再详细说明。</p>
<h2 id="Props"><a href="#Props" class="headerlink" title="Props"></a>Props</h2><p>props指的是Model中的属性定义。props定义了这个Model维护的状态对象包含哪些字段，各字段对应的又是什么类型。</p>
<p>拿开篇中的“商品”作为例子：</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; types &#125; from <span class="string">'mobx-state-tree'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> ProductItem = types.model(<span class="string">'ProductItem'</span>, &#123;</span><br><span class="line">    prodName: types.<span class="keyword">string</span>,</span><br><span class="line">    price: types.number,</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>types.model方法的第一个参数为Model设定了名称，第二个参数传入了一个对象，这个对象就是Model的props。</p>
<p>上面代码中，指定了ProductItem这个Model包含了类型为string的prodName属性和类型为number的price属性。</p>
<p>注意，可以省略types.model的第二个参数，然后使用model.props方法来定义props。</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> ProductItem = types</span><br><span class="line">    .model(<span class="string">'ProductItem'</span>)</span><br><span class="line">    .props(&#123;</span><br><span class="line">        prodName: types.<span class="keyword">string</span>,</span><br><span class="line">        price: types.number,</span><br><span class="line">    &#125;);</span><br></pre></td></tr></table></figure>
<p>types.model方法的第一个参数为Model设定了名称，第二个参数传入了一个对象，这个对象就是Model的props。</p>
<p>上面代码中，指定了ProductItem这个Model包含了类型为string的prodName属性和类型为number的price属性。</p>
<p>注意，可以省略types.model的第二个参数，然后使用model.props方法来定义props。</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> ProductItem = types</span><br><span class="line">    .model(<span class="string">'ProductItem'</span>)</span><br><span class="line">    .props(&#123;</span><br><span class="line">        prodName: types.<span class="keyword">string</span>,</span><br><span class="line">        price: types.number,</span><br><span class="line">    &#125;);</span><br></pre></td></tr></table></figure>
<p>上面的两份代码得到的ProductItem是相同的（实际上有一些细微差别，但可以完全忽略）。</p>
<p>定义了props之后，在Model的实例上可以访问到相应的字段：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> productItem = ProductItem.create(&#123;<span class="attr">prodName</span>: <span class="string">'商品标题xxx'</span>, <span class="attr">price</span>: <span class="number">99.9</span>&#125;);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(productItem.prodName); <span class="comment">// 商品标题xxx</span></span><br><span class="line"><span class="built_in">console</span>.log(productItem.price); <span class="comment">// 99.9</span></span><br></pre></td></tr></table></figure>
<p>上面的两份代码得到的ProductItem是相同的（实际上有一些细微差别，但可以完全忽略）。</p>
<p>定义了props之后，在Model的实例上可以访问到相应的字段：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> productItem = ProductItem.create(&#123;<span class="attr">prodName</span>: <span class="string">'商品标题xxx'</span>, <span class="attr">price</span>: <span class="number">99.9</span>&#125;);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(productItem.prodName); <span class="comment">// 商品标题xxx</span></span><br><span class="line"><span class="built_in">console</span>.log(productItem.price); <span class="comment">// 99.9</span></span><br></pre></td></tr></table></figure>
<h2 id="Views"><a href="#Views" class="headerlink" title="Views"></a>Views</h2><p>views是Model中一系列衍生数据或获取衍生数据的方法的集合，类似Vue组件的computed计算属性。</p>
<p>在定义Model时，可以使用model.views方法定义views。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> ProductItem = types</span><br><span class="line">    .model(<span class="string">'ProductItem'</span>, &#123;</span><br><span class="line">        prodName: types.string,</span><br><span class="line">        price: types.number,</span><br><span class="line">        discount: types.number,</span><br><span class="line">    &#125;)</span><br><span class="line">    .views(<span class="function"><span class="params">self</span> =&gt;</span> (&#123;</span><br><span class="line">        <span class="keyword">get</span> priceAfterDiscount () &#123;</span><br><span class="line">            <span class="keyword">return</span> self.price - self.discount;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;));</span><br></pre></td></tr></table></figure>
<p>上面代码中，定义了priceAfterDiscount，表示商品的折后价格。调用.views方法时，传入的是一个方法，方法的参数self是当前Model的实例，方法需要返回一个对象，表示Model的views集合。</p>
<p>需要注意的是，定义views时有两种选择，使用getter或者不使用。使用getter时，衍生数据的值会被缓存直到依赖的数据发送变化。而不使用时，需要通过方法调用的方式获取衍生数据，无法对计算结果进行缓存。尽可能使用getter，有助于提升应用的性能。</p>
<h2 id="Actions"><a href="#Actions" class="headerlink" title="Actions"></a>Actions</h2><p>actions是用于更新状态的方法集合。</p>
<p>在创建Model时，使用model.actions方法来定义actions：</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Root = types</span><br><span class="line">    .model(<span class="symbol">'Root</span>', &#123;</span><br><span class="line">        <span class="built_in">str</span>: types.string,</span><br><span class="line">    &#125;)</span><br><span class="line">    .actions(<span class="keyword">self</span> =&gt; (&#123;</span><br><span class="line">        setStr (val: string) &#123;</span><br><span class="line">            <span class="keyword">self</span>.<span class="built_in">str</span> = val;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;));</span><br><span class="line">    </span><br><span class="line"><span class="keyword">const</span> root = Root.create(&#123;<span class="built_in">str</span>: <span class="symbol">'mobx</span>'&#125;);</span><br><span class="line">root.setStr(<span class="symbol">'mst</span>');</span><br></pre></td></tr></table></figure>
<p>在安全模式下，所有对状态的更新操作必须在actions中执行，否则会报错：</p>
<p><img src="/blog/2019/10/07/MobX-State-Tree数据组件化开发-1-：MST基础/16882cfe6d826fff.jpg" alt></p>
<p>可以使用unprotect方法解除安全模式（不推荐）：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; types, unprotect &#125; <span class="keyword">from</span> <span class="string">'mobx-state-tree'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> Root = types.model(...);</span><br><span class="line">unprotect(Root);</span><br><span class="line"></span><br><span class="line">root.str = <span class="string">'mst'</span>; <span class="comment">// ok</span></span><br></pre></td></tr></table></figure>
<p>除了通常意义上用来更新状态的actions外，在model.actions方法中，还可以设置一些特殊的actions：</p>
<ul>
<li>afterCreate</li>
<li>afterAttach</li>
<li>beforeDetach</li>
<li>beforeDestroy</li>
</ul>
<p>从名字上可以看出来，上面四位都是生命周期方法，可以使用他们在Model的各个生命周期执行一些操作：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Model = types</span><br><span class="line">    .model(...)</span><br><span class="line">    .actions(<span class="function"><span class="params">self</span> =&gt;</span> (&#123;</span><br><span class="line">        afterCreate () &#123;</span><br><span class="line">            <span class="comment">// 执行一些初始化操作</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;));</span><br></pre></td></tr></table></figure>
<p>具体的MST生命周期在后续文章中再详细讨论。</p>
<h2 id="异步Action、Flow"><a href="#异步Action、Flow" class="headerlink" title="异步Action、Flow"></a>异步Action、Flow</h2><p>异步更新状态是非常常见的需求，MST从底层支持异步action。</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> model = types</span><br><span class="line">    .model(...)</span><br><span class="line">    .actions(self =&gt; (&#123;</span><br><span class="line">        <span class="comment">// async/await</span></span><br><span class="line">        <span class="function"><span class="keyword">async</span> <span class="title">getData</span> (<span class="params"></span>)</span> &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">const</span> data = <span class="keyword">await</span> api.getData();</span><br><span class="line">                ...</span><br><span class="line">            &#125; <span class="keyword">catch</span> (err) &#123;</span><br><span class="line">                ...</span><br><span class="line">            &#125;</span><br><span class="line">            ...</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="comment">// promise</span></span><br><span class="line">        updateData () &#123;</span><br><span class="line">            <span class="keyword">return</span> api.updateData()</span><br><span class="line">                .then(...)</span><br><span class="line">                .<span class="keyword">catch</span>(...);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;));</span><br></pre></td></tr></table></figure>
<p>需要注意，上文提到过：</p>
<blockquote>
<p>在安全模式下，所有对状态的更新操作必须在actions中执行，否则会报错</p>
</blockquote>
<p>若使用Promise、async/await来编写异步Action，在异步操作之后更新状态时，代码执行的上下文会脱离action，导致状态在action之外被更新而报错。这里有两种解决办法：</p>
<ol>
<li>将更新状态的操作单独封装成action</li>
<li>编写一个runInAction的action在异步操作中使用</li>
</ol>
<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 方法1</span></span><br><span class="line">const Model = types</span><br><span class="line">    .model(<span class="params">...</span>)</span><br><span class="line">    .actions(<span class="built_in">self</span> =&gt; (&#123;</span><br><span class="line">        setLoading (loading: <span class="built_in">boolean</span>) &#123;</span><br><span class="line">            <span class="built_in">self</span>.loading = loading;</span><br><span class="line">        &#125;,</span><br><span class="line">        setData (<span class="built_in">data</span>: any) &#123;</span><br><span class="line">            <span class="built_in">self</span>.<span class="built_in">data</span> = <span class="built_in">data</span>;</span><br><span class="line">        &#125;,</span><br><span class="line">        async getData () &#123;</span><br><span class="line">            <span class="params">...</span></span><br><span class="line">            <span class="built_in">self</span>.setLoading(<span class="literal">true</span>); <span class="comment">// 这里因为在异步操作之前，直接赋值self.loading = true也ok</span></span><br><span class="line">            const <span class="built_in">data</span> = await api.getData();</span><br><span class="line">            <span class="built_in">self</span>.setData(<span class="built_in">data</span>);</span><br><span class="line">            <span class="built_in">self</span>.setLoading(<span class="literal">false</span>);</span><br><span class="line">            <span class="params">...</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;));</span><br><span class="line">    </span><br><span class="line"><span class="comment">// 方法2</span></span><br><span class="line">const Model = types</span><br><span class="line">    .model(<span class="params">...</span>)</span><br><span class="line">    .actions(<span class="built_in">self</span> =&gt; (&#123;</span><br><span class="line">        runInAction (fn: () =&gt; any) &#123;</span><br><span class="line">            fn();</span><br><span class="line">        &#125;,</span><br><span class="line">        async getData () &#123;</span><br><span class="line">            <span class="params">...</span></span><br><span class="line">            <span class="built_in">self</span>.runInAction(() =&gt; <span class="built_in">self</span>.loading = <span class="literal">true</span>);</span><br><span class="line">            const <span class="built_in">data</span> = await api.getData();</span><br><span class="line">            <span class="built_in">self</span>.runInAction(() =&gt; &#123;</span><br><span class="line">                <span class="built_in">self</span>.<span class="built_in">data</span> = <span class="built_in">data</span>;</span><br><span class="line">                <span class="built_in">self</span>.loading = <span class="literal">false</span>;</span><br><span class="line">            &#125;);</span><br><span class="line">            <span class="params">...</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;));</span><br></pre></td></tr></table></figure>
<p>方法1需要额外封装N个action，比较麻烦。方法2封装一次就可以多次使用。</p>
<p>但是在某些情况下，两种方法都不够完美：一个异步action被分割成了N个action调用，无法使用MST的插件机制实现整个异步action的原子操作、撤销/重做等高级功能。</p>
<p>为了解决这个问题，MST提供了flow方法来创建异步action：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">import &#123; types, flow &#125; from <span class="string">'mobx-state-tree'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> model = types</span><br><span class="line">    .model(...)</span><br><span class="line">    .actions(<span class="keyword">self</span> =&gt; &#123;</span><br><span class="line">        <span class="keyword">const</span> getData = flow(<span class="function"><span class="keyword">function</span> * <span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">self</span>.loading = <span class="keyword">true</span>;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">const</span> data = <span class="keyword">yield</span> api.getData();</span><br><span class="line">                <span class="keyword">self</span>.data = data;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (err) &#123;</span><br><span class="line">                ...</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">self</span>.loading = <span class="keyword">false</span>;</span><br><span class="line">        &#125;);</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> &#123;</span><br><span class="line">            getData</span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;)</span><br></pre></td></tr></table></figure>
<p>使用flow方法需要传入一个generator function，在这个生成器方法中，使用yield关键字可以resolve异步操作。并且，在方法中可以直接给状态赋值，写起来更简单自然。</p>
<h2 id="Snapshot"><a href="#Snapshot" class="headerlink" title="Snapshot"></a>Snapshot</h2><p>snapshot即“快照”，表示某一时刻，Model的状态序列化之后的值。这个值是标准的JS对象。</p>
<p>使用getSnapshot方法获取快照：</p>
<figure class="highlight gams"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">import &#123; getSnapshot &#125; from <span class="string">'mobx-state-tree'</span>;</span><br><span class="line"></span><br><span class="line">cosnt <span class="keyword">Model</span> = types.<span class="keyword">model</span>(...);</span><br><span class="line">const <span class="keyword">model</span> = <span class="keyword">Model</span>.create(...);</span><br><span class="line"></span><br><span class="line">console.<span class="built-in">log</span>(getSnapshot(<span class="keyword">model</span>));</span><br></pre></td></tr></table></figure>
<p>使用applySnapshot方法可以更新Model的状态：</p>
<figure class="highlight clean"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; applySnapshot &#125; <span class="keyword">from</span> <span class="string">'mobx-state-tree'</span>;</span><br><span class="line"></span><br><span class="line">...</span><br><span class="line">applySnapshot(model, &#123;</span><br><span class="line">    msg: <span class="string">'hello'</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>通过applySnapshot方法更新状态时，传入的状态值必须匹配Model的类型定义，否则会报错：</p>
<p><img src="/blog/2019/10/07/MobX-State-Tree数据组件化开发-1-：MST基础/168831d879355c88.jpg" alt></p>
<p>getSnapshot及applySnapshot方法都可以用在Model的子Model上使用。</p>
<h2 id="Volatile-State"><a href="#Volatile-State" class="headerlink" title="Volatile State"></a>Volatile State</h2><p>在MST中，props对应的状态都是可持久化的，也就是可以序列化为标准的JSON数据。并且，props对应的状态必须与props的类型相匹配。<br>如果需要在Model中存储无需持久化，并且数据结构或类型无法预知的动态数据，可以设置为Volatile State。<br>Volatile State使用model.volatile方法定义：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; types &#125; <span class="keyword">from</span> <span class="string">'mobx-state-tree'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; autorun &#125; <span class="keyword">from</span> <span class="string">'mobx'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> Model = types</span><br><span class="line">    .model(<span class="string">'Model'</span>)</span><br><span class="line">    .volatile(<span class="function"><span class="params">self</span> =&gt;</span> (&#123;</span><br><span class="line">        anyData: &#123;&#125; <span class="keyword">as</span> <span class="built_in">any</span></span><br><span class="line">    &#125;))</span><br><span class="line">    .actions(<span class="function"><span class="params">self</span> =&gt;</span> (&#123;</span><br><span class="line">      runInAction (fn: <span class="function"><span class="params">()</span> =&gt;</span> <span class="built_in">any</span>) &#123;</span><br><span class="line">        fn();</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;));</span><br><span class="line">    </span><br><span class="line"><span class="keyword">const</span> model = Model.create();</span><br><span class="line"></span><br><span class="line">autorun(<span class="function"><span class="params">()</span> =&gt;</span> <span class="built_in">console</span>.log(model.anyData));</span><br><span class="line"></span><br><span class="line">model.runInAction(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">  model.anyData = &#123;a: <span class="number">1</span>&#125;;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">model.runInAction(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">  model.anyData.a = <span class="number">2</span>;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>和actions及views一样，model.volatile方法也要传入一个参数为Model实例的方法，并返回一个对象。</p>
<p>运行上面代码，可得到如下输出：</p>
<p><img src="/blog/2019/10/07/MobX-State-Tree数据组件化开发-1-：MST基础/168837fdfbd02e5d.jpg" alt></p>
<p>代码中使用Mobx的autorun方法监听并打印model.anyData的值，图中一共看到2次输出：</p>
<p>anyData的初始值<br>第一次更新anyData后的值</p>
<p>但是第二次为anyData.a赋值并没有执行autorun。<br>由此可见，Volatile State的值也是Observable，但是只会响应引用的变化，是一个非Deep Observable。<br>。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/mobx-state-tree/" rel="tag"># mobx-state-tree</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/10/07/MobX-State-Tree数据组件化开发-0-：开篇/" rel="next" title="[MobX State Tree数据组件化开发][0]：开篇">
                <i class="fa fa-chevron-left"></i> [MobX State Tree数据组件化开发][0]：开篇
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/10/07/MobX-State-Tree数据组件化开发-2-：实例-TodoList/" rel="prev" title="[MobX State Tree数据组件化开发][2]：实例-TodoList">
                [MobX State Tree数据组件化开发][2]：实例-TodoList <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">lhweb</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">39</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">25</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/blog/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#预备知识"><span class="nav-number">1.</span> <span class="nav-text">预备知识</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#安装"><span class="nav-number">2.</span> <span class="nav-text">安装</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Type、Model"><span class="nav-number">3.</span> <span class="nav-text">Type、Model</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Props"><span class="nav-number">4.</span> <span class="nav-text">Props</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Views"><span class="nav-number">5.</span> <span class="nav-text">Views</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Actions"><span class="nav-number">6.</span> <span class="nav-text">Actions</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#异步Action、Flow"><span class="nav-number">7.</span> <span class="nav-text">异步Action、Flow</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Snapshot"><span class="nav-number">8.</span> <span class="nav-text">Snapshot</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Volatile-State"><span class="nav-number">9.</span> <span class="nav-text">Volatile State</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">lhweb</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
